/* Raw sequence accumulator.

   This file is part of khipu.

   khipu is free software: you can redistribute it and/or modify
   it under the terms of the GNU Lesser General Public License as published by
   the Free Software Foundation; either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public License
   along with this program.  If not, see <https://www.gnu.org/licenses/>.  */

#ifndef __UTILS_RAW_ACC__
#define __UTILS_RAW_ACC__   1

#include "../memory.hpp"

KP_DECLS_BEGIN

template <typename T>
struct raw_acc
{
  T *ptr = nullptr;
  uint32_t alloc = 0;

  raw_acc (uint32_t isz)
    {
      this->ptr = T::alloc_raw (this->alloc = isz);
      this->ptr->init_vo ();
      this->ptr->len_ref() = 0;
    }

  raw_acc () : raw_acc (upsize (0))
    {
    }

  void expand (uint32_t size)
    {
      if (size < this->alloc)
        return;

      T *tmp = T::alloc_raw (this->alloc = upsize (size + 1));

      tmp->len_ref() = this->ptr->len_ref ();
      memcpy (tmp->data_ptr (), this->ptr->data_ptr (),
        tmp->len_ref () * sizeof (*tmp->data_ptr ()));

      xfree (this->ptr);
      this->ptr = tmp;
    }

  void add_data (const void *data, uint32_t size)
    {
      expand (this->ptr->len_ref () + size);
      memcpy ((char *)this->ptr->data_ptr () +
        this->ptr->len_ref (), data, size);
      this->ptr->len_ref() += size;
    }

  void add_obj (object obj)
    {
      expand (this->ptr->len_ref () + 1);
      ((object *)this->ptr->data_ptr ())[this->ptr->len_ref()++] = obj;
    }

  object as_obj () const
    {
      return (this->ptr->as_obj ());
    }

  T* get ()
    {
      return (this->ptr);
    }

  T* release ()
    {
      T *ret = this->ptr;
      this->ptr = nullptr;
      return (ret);
    }

  ~raw_acc ()
    {
      xfree (this->ptr);
    }
};

KP_DECLS_END

#endif
